<?php
namespace App\Http\Controllers\V1;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UserController extends ApiController
{
    public function store()
    {
        $userMdl = new User;
        $userMdl->name = 'no1';
        $userMdl->password = password_hash('123456', PASSWORD_DEFAULT);

        $userMdl->save();

        return $this->success([]);
    }

    /**
     * 填充返回token的数据
     *
     * @param string $token
     * @return void
     * @param
     * @author liangl
     */
    private function formatToken(string $token)
    {
        $retData = [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->provider()->factory()->getTTL() * 60
        ];

        return $this->success($retData);
    }
    
    /**
     * 登陆
     *
     * @param Request $request
     * @return void
     * @param
     * @author liangl
     */
    public function login(Request $request)
    {
        $token = $this->provider()->attempt($request->only('name', 'password'));
        if (!$token) {
            return $this->error('登陆失败');
        }

        return $this->formatToken($token);
    }

    /**
     * 取用户信息
     *
     * @return void
     * @param
     * @author liangl
     */
    public function me()
    {
        $user = $this->provider()->user();

        return $this->success($user);
    }

    /**
     * 刷新token
     *
     * @return void
     * @param
     * @author liangl
     */
    public function refresh()
    {
        return $this->formatToken($this->provider()->parseToken()->refresh());
    }
}
